const Koa = require('koa');
const { connect } = require('./db');
const registerRoutes = require('./routers');
const koaBody = require('koa-body');
const { middleware: jwtMiddleware, catchTokenError } = require('./helpers/token');
const { logMiddleware } = require('./helpers/log');
const cors = require('@koa/cors');

const app = new Koa();

connect().then(() => {
  // 解决跨域问题
  app.use(cors());
  app.use(koaBody());

  app.use(catchTokenError);
  jwtMiddleware(app);

  app.use(logMiddleware);

  // 注册路由
  registerRoutes(app);

  // 开启http服务
  // 接收http请求，并作出处理，处理完成后进行响应
  app.listen(3000, () => {
    console.log('>>> 电商 后端服务器启动，端口号：3000');
  });
});
